package com.ruoyi.develop.goodsInvoice.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.constants.BusinessConstants;
import com.ruoyi.develop.goodsInvoiceApplyDetail.domain.GoodsInvoiceApplyDetail;
import com.ruoyi.develop.goodsInvoiceApplyDetail.service.IGoodsInvoiceApplyDetailService;
import com.ruoyi.develop.goodsInvoiceInfo.domain.GoodsInvoiceInfo;
import com.ruoyi.develop.goodsInvoiceInfo.service.IGoodsInvoiceInfoService;
import com.ruoyi.develop.goodsSale.domain.GoodsSale;
import com.ruoyi.develop.goodsSale.service.IGoodsSaleService;
import com.ruoyi.develop.projectBaseInfo.domain.ProjectBaseInfo;
import com.ruoyi.develop.projectBaseInfo.mapper.ProjectBaseInfoMapper;
import com.ruoyi.develop.projectBaseInfo.service.IProjectBaseInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.develop.goodsInvoice.mapper.GoodsInvoiceMapper;
import com.ruoyi.develop.goodsInvoice.domain.GoodsInvoice;
import com.ruoyi.develop.goodsInvoice.service.IGoodsInvoiceService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 发票管理Service业务层处理
 *
 * @author qh
 * @date 2023-01-05
 */
@Service
public class GoodsInvoiceServiceImpl implements IGoodsInvoiceService {
    @Resource
    private GoodsInvoiceMapper goodsInvoiceMapper;
    @Resource
    private IGoodsInvoiceService goodsInvoiceService;
    @Autowired
    private IGoodsSaleService goodsSaleService;
    @Autowired
    private IProjectBaseInfoService projectBaseInfoService;
    @Autowired
    private IGoodsInvoiceInfoService goodsInvoiceInfoService;
    @Autowired
    private IGoodsInvoiceApplyDetailService goodsInvoiceApplyDetailService;

    @Autowired
    private ProjectBaseInfoMapper projectBaseInfoMapper;

    /**
     * 查询发票管理
     *
     * @param id 发票管理主键
     * @return 发票管理
     */
    @Override
    public GoodsInvoice selectById(String id) {
        return goodsInvoiceMapper.selectById(id);
    }

    /**
     * 查询发票管理列表
     *
     * @param entity 发票管理
     * @return 发票管理
     */
    @Override
    public List<GoodsInvoice> selectList(GoodsInvoice entity) {
        return goodsInvoiceMapper.selectList(entity);
    }

    @Override
    public List<GoodsInvoice> selectListWhx(GoodsInvoice entity) {
        return goodsInvoiceMapper.selectListWhx(entity);
    }

    /**
     * 新增发票管理
     *
     * @param entity 发票管理
     * @return 结果
     */
    @Override
    @Transactional(readOnly = false)
    public AjaxResult insert(GoodsInvoice entity) {
        if (StringUtils.isBlank(entity.getId())) {
            entity.setId(IdUtils.fastSimpleUUID());
        }
        entity.setCreateBy(SecurityUtils.getUsername());
        entity.setCreateTime(DateUtils.getNowDate());
        int i = goodsInvoiceMapper.insert(entity);
        return AjaxResult.success(i);
    }

    /**
     * 修改发票管理
     *
     * @param entity 发票管理
     * @return 结果
     */
    @Override
    public int update(GoodsInvoice entity) {
        entity.setUpdateBy(SecurityUtils.getUsername());
        entity.setUpdateTime(DateUtils.getNowDate());
        return goodsInvoiceMapper.update(entity);
    }

    /**
     * 批量删除发票管理
     *
     * @param ids 需要删除的发票管理主键
     * @return 结果
     */
    @Override
    public int deleteByIds(String[] ids) {
        return goodsInvoiceMapper.deleteByIds(ids);
    }

    /**
     * 删除发票管理信息
     *
     * @param id 发票管理主键
     * @return 结果
     */
    @Override
    public int deleteById(String id) {
        return goodsInvoiceMapper.deleteById(id);
    }

    public void updateMoney(String mainId) {
        GoodsInvoiceInfo invoiceInfoParam = new GoodsInvoiceInfo();
        invoiceInfoParam.setMainId(mainId);
        List<GoodsInvoiceInfo> invoiceInfos = goodsInvoiceInfoService.selectList(invoiceInfoParam);
        BigDecimal amountReal = BigDecimal.ZERO;
        for (GoodsInvoiceInfo invoiceInfo : invoiceInfos) {
            amountReal = amountReal.add(invoiceInfo.getInvoiceMoney());
        }
        GoodsInvoice entity = selectById(mainId);
        entity.setAmountReal(amountReal);
        entity.setRemaining(entity.getAmount().subtract(amountReal));
        entity.setType("xmkp");
        if (entity.getAmount().compareTo(entity.getAmountReal()) == 0) {
            entity.setStatus("ykp");
        } else if (entity.getAmount().compareTo(entity.getAmountReal()) > 0 && entity.getAmountReal().compareTo(BigDecimal.ZERO) > 0) {
            entity.setStatus("bfkp");
        } else if (entity.getAmount().compareTo(entity.getRemaining()) == 0) {
            entity.setStatus("wkp");
        }
        update(entity);
    }

    //订单批量开票
    @Override
    @Transactional
    public void insertBatch(GoodsInvoice goodsInvoice) {
        List<ProjectBaseInfo> rows = goodsInvoice.getColumns();
        if (!rows.isEmpty()) {
            for (ProjectBaseInfo projectBaseInfo : rows) {
                GoodsInvoice goodsInvoiceEntity = new GoodsInvoice();
                if (StringUtils.isBlank(goodsInvoiceEntity.getId())) {
                    goodsInvoiceEntity.setId(IdUtils.fastSimpleUUID());
                }
                goodsInvoiceEntity.setInvoiceCompany(goodsInvoice.getInvoiceCompany());
                goodsInvoiceEntity.setFiles(goodsInvoice.getFiles());
                goodsInvoiceEntity.setRemark(goodsInvoice.getRemark());

                goodsInvoiceEntity.setProjectId(projectBaseInfo.getId());
                goodsInvoiceEntity.setProjectName(projectBaseInfo.getName());
                goodsInvoiceEntity.setProjectNo(projectBaseInfo.getCode());
                goodsInvoiceEntity.setFrameworkCode(projectBaseInfo.getProjectCode());
                goodsInvoiceEntity.setFrameworkId(projectBaseInfo.getProjectId());

                goodsInvoiceEntity.setCustomerId(projectBaseInfo.getCustomId());
                goodsInvoiceEntity.setCustomerName(projectBaseInfo.getCustomName());
                goodsInvoiceEntity.setTaxNo(projectBaseInfo.getTaxcode());
                goodsInvoiceEntity.setAmount(projectBaseInfo.getTaxAmount());
                goodsInvoiceEntity.setRemaining(projectBaseInfo.getTaxAmount());
                goodsInvoiceEntity.setSaleId(projectBaseInfo.getSaleId());
                goodsInvoiceEntity.setSaleName(projectBaseInfo.getSalesmanName());
                goodsInvoiceEntity.setStatus(BusinessConstants.TAX_STATUS_0);
                goodsInvoiceEntity.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_WHX);
                goodsInvoiceEntity.setGongchengName(projectBaseInfo.getGongchengName());
                goodsInvoiceEntity.setDrawerId(SecurityUtils.getUserId());
                goodsInvoiceEntity.setDrawerName(SecurityUtils.getUsername());
                goodsInvoiceEntity.setCreateBy(SecurityUtils.getUsername());
                goodsInvoiceEntity.setCreateTime(DateUtils.getNowDate());
                goodsInvoiceMapper.insert(goodsInvoiceEntity);
                GoodsInvoiceApplyDetail goodsInvoiceApplyDetail = new GoodsInvoiceApplyDetail();
                goodsInvoiceApplyDetail.setApplyId(goodsInvoiceEntity.getId());
                goodsInvoiceApplyDetail.setAmount(goodsInvoiceEntity.getAmount());
                goodsInvoiceApplyDetail.setProjectId(goodsInvoiceEntity.getProjectId());
                goodsInvoiceApplyDetail.setProjectNo(goodsInvoiceEntity.getProjectNo());
                goodsInvoiceApplyDetailService.insert(goodsInvoiceApplyDetail);
                // 更新 订单上的开票金额
                projectBaseInfo.setTaxRemain(projectBaseInfo.getTaxRemain().subtract(goodsInvoiceEntity.getAmount()));
                projectBaseInfoService.update(projectBaseInfo);
            }
        }
    }

    //订单合并开票
    @Override
    @Transactional
    public void insertBatchAll(GoodsInvoice goodsInvoice) {
        List<ProjectBaseInfo> rows = goodsInvoice.getColumns();
        if (!rows.isEmpty()) {
            GoodsInvoice goodsInvoiceEntity = new GoodsInvoice();
            if (StringUtils.isBlank(goodsInvoiceEntity.getId())) {
                goodsInvoiceEntity.setId(IdUtils.fastSimpleUUID());
            }
            goodsInvoiceEntity.setInvoiceCompany(goodsInvoice.getInvoiceCompany());
            goodsInvoiceEntity.setFiles(goodsInvoice.getFiles());
            goodsInvoiceEntity.setRemark(goodsInvoice.getRemark());
            goodsInvoiceEntity.setCustomerId(goodsInvoice.getCustomerId());
            goodsInvoiceEntity.setCustomerName(goodsInvoice.getCustomerName());
            goodsInvoiceEntity.setTaxNo(goodsInvoice.getTaxNo());
            goodsInvoiceEntity.setAmount(goodsInvoice.getAmount());
            goodsInvoiceEntity.setRemaining(goodsInvoice.getAmount());
            goodsInvoiceEntity.setStatus(BusinessConstants.TAX_STATUS_0);
            goodsInvoiceEntity.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_WHX);
            goodsInvoiceEntity.setCreateBy(SecurityUtils.getUsername());
            goodsInvoiceEntity.setCreateTime(DateUtils.getNowDate());
            goodsInvoiceEntity.setDrawerId(SecurityUtils.getUserId());
            goodsInvoiceEntity.setDrawerName(SecurityUtils.getUsername());
            StringBuilder projectId = new StringBuilder();
            StringBuilder projectName = new StringBuilder();
            StringBuilder projectNo = new StringBuilder();

            for (ProjectBaseInfo entity : rows) {
                projectId.append(entity.getId()).append(",");
                projectName.append(entity.getName()).append(",");
                projectNo.append(entity.getCode()).append(",");
            }

            // 使用stream和Set去重
            List<ProjectBaseInfo> uniqueProject = rows.stream()
                    .collect(Collectors.collectingAndThen(
                            Collectors.toMap(ProjectBaseInfo::getProjectCode, p -> p, (existing, replacement) -> existing),
                            map -> new ArrayList<>(map.values())
                    ));

            StringBuilder frameworkCode = new StringBuilder();
            StringBuilder frameworkId = new StringBuilder();
            for (ProjectBaseInfo entity : uniqueProject) {
                frameworkCode.append(entity.getProjectCode()).append(",");
                frameworkId.append(entity.getProjectId()).append(",");
            }


            goodsInvoiceEntity.setFrameworkCode(frameworkCode.toString());
            goodsInvoiceEntity.setFrameworkId(frameworkId.toString());
            goodsInvoiceEntity.setProjectId(projectId.toString());
            goodsInvoiceEntity.setProjectName(projectName.toString());
            goodsInvoiceEntity.setProjectNo(projectNo.toString());
            goodsInvoiceEntity.setSaleId(rows.get(0).getSaleId());//业务员id
            goodsInvoiceEntity.setSaleName(rows.get(0).getSalesmanName());//业务员名字
            goodsInvoiceMapper.insert(goodsInvoiceEntity);
            // 插入开票明细
            for (ProjectBaseInfo projectBaseInfo : rows) {
                // 插入 开票申请 明细
                GoodsInvoiceApplyDetail goodsInvoiceApplyDetail = new GoodsInvoiceApplyDetail();
                goodsInvoiceApplyDetail.setApplyId(goodsInvoiceEntity.getId());
                goodsInvoiceApplyDetail.setAmount(projectBaseInfo.getTaxAmount());
                goodsInvoiceApplyDetail.setProjectId(projectBaseInfo.getId());
                goodsInvoiceApplyDetail.setProjectNo(projectBaseInfo.getCode());
                goodsInvoiceApplyDetailService.insert(goodsInvoiceApplyDetail);
                // 更新订单开票金额
                projectBaseInfo.setTaxRemain(projectBaseInfo.getTaxRemain().subtract(projectBaseInfo.getTaxAmount()));
                projectBaseInfoMapper.update(projectBaseInfo);
            }
        }
    }

    @Override
    public GoodsInvoice selectByInvoice(GoodsInvoice entity) {
        return goodsInvoiceMapper.selectByInvoice(entity);
    }
}
